#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <pthread.h>
#include <math.h>
#include "prefetch_lib.h"
#include <time.h>
#include <pthread.h>
#include <syslog.h>

#define N (32768/2)
#define NUMINTS  (N * N)
#define FILESIZE (NUMINTS * sizeof(int))
#define TOTALSIZE (4294967296/2)
#define BINS 100

int *mapa, *mapb;
int count[BINS];

int F() 
{    
    int i, j, k, s, m = 0;
    time_t t = time(0);

//    madvise(mapa, FILESIZE / 8, MADV_WILLNEED);

    for (i = 0; i < N * N; ++i) {
//      if (i % (N * N / 8) == 0)
//        madvise(mapa + (i + N * N / 8) * sizeof(int), FILESIZE / 8, MADV_WILLNEED);
    
      for (j = 0; j < 4; ++j)      
        m ^= mapa[i];
      
      if (i % (4096 * 4096 * 4) == 0) {
//        madvise(mapa + i + 10, 4096 * 4096 * 4, MADV_WILLNEED);
        time_t n = time(0);
        printf("[%lu] in i loop; i = %d done in %lu\n", pthread_self(), i, n - t);
        t = n;
      }
    }

    
    return m;
}

int main(int argc, char *argv[])
{
    int f, fda, fdb, i;
    
    turn_logging(1);
    fetch_init();
    mapa = (int*)mmap(0, FILESIZE, PROT_READ, MAP_SHARED, fda = open64("b", O_RDONLY), 0);


    printf("a: %x-%x\n", (unsigned int)mapa >> 12, (unsigned int)(mapa + N * N) >> 12);

    madvise(mapa, FILESIZE, MADV_RANDOM);
    madvise(mapa, FILESIZE / 4, MADV_WILLNEED);

    f = F();

    munmap(mapa, FILESIZE);

    close(fda);

    return f;
}
